<template>
  <div>
    <el-form @submit.native.prevent :inline="true">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="主本名称"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <select-farm-org
          v-model="params['org_class.eq']"
          placeholder="主体类型"
          clearable
          @change="getData()"
          class="form-control-ml"
        ></select-farm-org>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="startDate"
          placeholder="申请起始时间"
          class="form-control-ml"
          @change="dateChange"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="endDate"
          placeholder="申请截止时间"
          class="form-control-ml"
          @change="dateChange"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="受理状态"
          v-model="params['is_approval.eq']"
          clearable
          :options="enumApproval"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumRecommend"
          @change="getData()"
          clearable
          v-model="params['recommend_status.eq']"
          placeholder="推荐状态"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel(exportTableName)"
        >
          导出
        </el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button
          icon="el-icon-folder-checked"
          type="primary"
          class="btn-long"
          @click="handleRecommend"
        >
          推荐
        </el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button
          type="primary"
          icon="el-icon-plus"
          v-if="classType && isArchiveManager"
          @click="handleEdit"
        >
          新增
        </el-button>
      </el-form-item>
    </el-form>
    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:status="scope">
        <span class="badge" :class="`badge-${scope.row.statusStyle}`">
          {{ scope.row.statusLabel }}
        </span>
        <div class="text-small" v-if="+scope.row.is_approval === 2">
          {{ scope.row.confuse_des }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :page-sizes="[15, 100, 200, 500, 1000]"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <pepper-edit
      :visible.sync="editVisible"
      @success="getData()"
      :table-id="tableId"
      :ind-code="classType"
    ></pepper-edit>

    <main-business-view-dialog
      :visible.sync="viewVisible"
      :query-id="queryId"
    ></main-business-view-dialog>

    <recom-dialog
      :visible.sync="recomVisible"
      @success="getData()"
      :business-code="classType"
      @dismiss="recomVisible = false"
    ></recom-dialog>
  </div>
</template>

<script>
import PepperEdit from '@/gov/views/bus/import/class/components/PepperEdit'
import { mapGetters } from 'vuex'
import { excelJsonExport, columnToAbc } from '@vimi/utils-tool'
import SelectAddress from '@/components/select/SelectAddress'
import SelectFarmOrg from '@/components/select/SelectFarmOrg'
import MainBusinessViewDialog from '@/gov/views/bus/import/class/MainBusinessViewDialog'
import { enumApproval, enumApprovalStyle } from '@/gov/views/bus/import/class/components/enum'
import { enumBusinessType } from '@/gov/views/bus/import/class/components/PepperEdit'
import { arrayFromString } from '@vimi/utils-tool'
import { attachAdapter } from '@/bank/components/attach/index'
import RecomDialog from '@/gov/views/bus/track/recom/components/RecomDialog'
export default {
  components: {
    SelectAddress,
    SelectFarmOrg,
    PepperEdit,
    MainBusinessViewDialog,
    RecomDialog,
  },
  props: {
    classType: String,
  },
  data() {
    return {
      enumApproval,
      enumRecommend: {
        0: '未推荐',
        1: '已推荐',
      },
      enmuBoothType: {
        1: '租赁',
        2: '自有',
      },
      params: {
        index: 1,
        size: 15,
        customer_name: '',
      },
      order: { create_time: 'DESC' },
      tableColumns: [
        { attrs: { label: '客户名称', prop: 'customer_name', align: 'center' } },
        { attrs: { label: '经营地址', prop: 'address', align: 'center' } },
        { attrs: { label: '主体类型', prop: 'org_class_name', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
        { attrs: { label: '证件号', prop: 'idCard', align: 'center' } },
        { attrs: { label: '申请金额(万元)', prop: 'apply_funds', align: 'center' } },
        {
          attrs: { label: '推荐状态', prop: 'recommendLabel', align: 'center' },
          process: (v, row) => ({
            attrs: { attrs: { class: `text-${row.recommendStyle}` } },
          }),
        },
        {
          attrs: { label: '受理状态', prop: 'statusLabel', align: 'center' },
          slot: 'status',
        },
        {
          attrs: { label: '操作', align: 'center', width: 100 },
          operations: [
            {
              content: '修改信息',
              icon: 'fa fa-edit',
              event: this.handleEdit,
              ifRender: row => +row.recommend_status === 0,
            },
            { content: '查看', icon: 'fa fa-search', event: this.handleView },
          ],
        },
      ],
      loading: false,
      totalCount: 0,
      tableData: [],
      tableName: 'credit_industrial',
      editVisible: false,
      tableId: '',
      formData: {},
      viewVisible: false,
      queryId: '',
      exportLoading: false,
      startDate: '',
      endDate: '',
      uploadVisible: false,
      recomVisible: false,
    }
  },
  computed: {
    ...mapGetters(['userId', 'user', 'job', 'provinceMainBusinessEnum']),
    isArchiveManager() {
      return this.user.scopeArr.includes(this.classType)
    },
    isCorp() {
      return this.job === 'org_corp'
    },
    exportTableName() {
      return `产业专班-${this.provinceMainBusinessEnum[this.classType]}`
    },
    queryAddressCode() {
      return this.user.queryAddressCode || this.user.addressCode
    },
  },
  watch: {
    classType: {
      handler: function () {
        if (!this.classType) {
          return
        }
        this.params['main_business_code.eq'] = this.classType
        if (this.isArchiveManager) {
          this.params['orWhere.address_code.endlike'] = this.queryAddressCode.replace(/0+$/g, '')
          this.params['orWhere.submit_person.eq'] = this.userId
        } else {
          this.params['submit_person.eq'] = this.userId
        }
        this.getData()
      },
      immediate: true,
    },
  },
  created() {
    this.params['main_business_code.eq'] = this.classType
  },
  mounted() {},
  methods: {
    handleRecommend() {
      this.recomVisible = true
    },
    getAttach(data) {
      return arrayFromString(data)
        .map(img => {
          return { url: img, name: img.replace(/.*\/(.*)$/, '$1'), attachment: img }
        })
        .map(item => {
          return { ...item, ...attachAdapter(item) }
        })
    },
    handleSizeChange(val) {
      this.params.size = val
      this.getData(1)
    },
    onSelect() {
      return true
    },
    dateChange() {
      this.params['create_time.gte'] = this.startDate || ''
      this.params['create_time.lte'] = this.endDate ? this.endDate + ' 23:59:59' : ''
      this.getData()
    },
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data ?? {}
          this.tableData = (data?.data ?? []).map(item => {
            item.idCard = item.register_no || item.lender_idcard
            item.recommendLabel = this.enumRecommend[item.recommend_status] || ''
            item.recommendStyle = enumApprovalStyle[item.recommend_status] || ''

            item.statusLabel = enumApproval[item.is_approval]
            item.statusStyle = enumApprovalStyle[item.is_approval]
            return item
          })
          this.totalCount = data?.totalCount ?? 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleEdit(row = {}) {
      this.formData = { ...row }
      this.tableId = row.credit_industrial_id
      this.editVisible = true
    },
    handleView(row = {}) {
      this.queryId = row.credit_industrial_id
      this.viewVisible = true
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(
          this.$serviceName,
          this.tableName,
          { ...params, subKey: 'credit_industrial_pepper.credit_industrial_id' },
          {
            // N1business_type: 'asc',
            N2create_time: 'desc',
          }
        )
      )
    },
    async exportExcel(filename) {
      const exportTable = [
        { label: '序号', prop: 'index' },
        { label: '主体名称', prop: 'customer_name' },
        { label: '经营地址', prop: 'address' },
        { label: '主体类型', prop: 'org_class_name' },
        { label: '营业证号', prop: 'register_no' },
        { label: '负责人', prop: 'corp_name' },
        { label: '负责人身份证', prop: 'lender_idcard' },
        { label: '联系电话', prop: 'mobile_no' },
        { label: '经营年限', prop: 'bussiness_years' },
        // 金融信息
        { label: '资产总额', prop: 'assets_funds' },
        { label: '资产情况', prop: 'assets_des' },
        { label: '负债情况', prop: 'debt_des' },
        { label: '负债总额', prop: 'debt_funds' },
        { label: '是否涉诉', prop: 'isLitigation' },
        { label: '涉诉信息', prop: 'litigation_des' },
        // 贷款信息
        { label: '贷款产品', prop: 'project_type_name' },
        { label: '申请金额', prop: 'apply_funds' },
        { label: '贷款年限', prop: 'load_year' },
        { label: '贷款用途', prop: 'funds_use_dir' },
        { label: '贷款意向银行', prop: 'bank_name' },
        { label: '是否有推荐函', prop: 'isRecommendLetter' },
        // 经营信息
        { label: '产业类型', prop: 'main_business' },
        { label: '经营类型', prop: 'businessType' },
        // 种植类详细经营信息
        { label: '种植品种', prop: 'plantCategory1' },
        { label: '近12个月产量(吨)', prop: 'output1' },
        { label: '近12个月销售收入(万元)', prop: 'sellIncome1' },
        { label: '是否购买农业保险', prop: 'isBuyInsurance1' },
        // 加工类详细经营信息
        { label: '厂房面积', prop: 'workshopArea2' },
        { label: '生产品种', prop: 'produceCategory2' },
        { label: '从业人数', prop: 'empTotal2' },
        { label: '近12个月产量', prop: 'output2' },
        { label: '近12个月销售收入', prop: 'sellIncome2' },
        { label: '近12个月税收情况', prop: 'taxDes2' },
        { label: '是否符合国家环保政策', prop: 'isFitEnv2' },
        // 商贸流通类详细经营信息
        { label: '近12个月收入', prop: 'sellIncome3' },
        { label: '是否有烘干线', prop: 'isDryLine3' },
        { label: '烘干线数量', prop: 'dryCount3' },
        { label: '是否有固定摊位', prop: 'isFixBooth3' },
        { label: '摊位面积', prop: 'boothArea3' },
        { label: '自有/租赁', prop: 'boothType3' },
      ]
      const header = {}
      const headerCellStyles = {}
      const columns = exportTable.map((item, i) => {
        const { prop, label } = item || {}
        header[prop] = label
        headerCellStyles[`${columnToAbc(i)}1`] = { font: { bold: true } }
        headerCellStyles[`${columnToAbc(i)}2`] = { font: { bold: true } }
        return prop
      })
      this.exportLoading = true
      const { index, size, ...params } = this.params
      const [res = {}] = await this.fetchData(params)
      const title = {
        index: '序号',
        customer_name: '基础信息',
        assets_funds: '金融信息',
        project_type_name: '贷款信息',
        main_business: '经营信息',
        plantCategory1: '种植类详细经营信息',
        workshopArea2: '加工类详细经营信息',
        sellIncome3: '商贸流通类详细经营信息',
      }
      const enumIsOrN = {
        0: '否',
        1: '是',
      }
      const data = (res.data || []).map((item, index) => {
        item.index = index + 1
        item.isLitigation = enumIsOrN[item.is_litigation]
        item.isRecommendLetter = enumIsOrN[item.is_recommend_letter]
        const detail = item.credit_industrial_pepper?.[0] ?? {}
        item.businessType = enumBusinessType[detail.business_type]
        // const keys = ['plant_category']
        // keys.forEach(key => {
        //   item[key] = detail[key]
        // })
        if (+detail.business_type === 1) {
          item.output1 = detail.output
          item.plantCategory1 = detail.plant_category
          item.sellIncome1 = detail.sell_income
          item.isBuyInsurance1 = enumIsOrN[detail.is_buy_insurance]
        }
        if (+detail.business_type === 2) {
          item.workshopArea2 = detail.workshop_area
          item.produceCategory2 = detail.produce_category
          item.empTotal2 = detail.emp_total
          item.output2 = detail.output
          item.sellIncome2 = detail.sell_income
          item.isFitEnv2 = enumIsOrN[detail.is_fit_env]
          item.taxDes2 = detail.tax_des
        }
        if (+detail.business_type === 3) {
          item.sellIncome3 = detail.sell_income
          item.isDryLine3 = enumIsOrN[detail.is_dry_line]
          item.dryCount3 = detail.dry_count || 0
          item.isFixBooth3 = enumIsOrN[detail.is_fix_booth]
          item.boothArea3 = detail.booth_area || 0
          item.boothType3 = this.enmuBoothType[detail.booth_type]
        }

        return item
      })

      excelJsonExport({
        columns,
        data: [title, header, ...data],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        merges: ['A1:A2', 'B1:I1', 'J1:O1', 'P1:U1', 'V1:W1', 'X1:AA1', 'AB1:AH1', 'AI1: AN1'],
        cellStyles: {
          ...headerCellStyles,
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
</style>
